package org.redhat.auth.security.taglibs;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.StrutsException;
import org.apache.struts2.components.UIBean;
import org.redhat.auth.security.util.AuthAuthorizeUtil;

import com.opensymphony.xwork2.util.ValueStack;

public class TagAuthorize extends UIBean {

	private String url;

	private boolean allAuthorized = true;

	private String role;

	public TagAuthorize(ValueStack stack, HttpServletRequest request,
			HttpServletResponse response) {
		super(stack, request, response);
	}

	/**
	 * 权限检查核心方法 规则：
	 * 
	 *   判断用户是否拥有某个角色 
	 * 1 <@auth.authorize role="ROLE_ADMIN"></@auth.authorize>
	 * 
	 *   allAuthorized=true 必须所有角色同时具有才为真 allAuthorized=flase 拥有其中任意一个角色便返回true 2
	 * <@auth.authorize role="ROLE_ADMIN;ROLE_USER" allAuthorized="true"></@auth.authorize>
	 *  
	 *   判断用户是否拥有访问某url的权限 
	 * 3 <@auth.authorize url="/index.action"></auth.authorize>
	 * 
	 *    allAuthorized=true 只有拥有所有url的访问控制权限时，返回true --allAuthorized=false,拥有任意一个url访问权限便可 
	 * 4 <@auth.authorize url="/index.action;/account/list.action" allAuthorized="false"></@auth.authroize>
	 * 
	 * @return
	 */
	private boolean authorizeCheck() {
		if (role == null && url == null) {
			throw new StrutsException("不正确的标签写法<@auth.authorize/>");
		}

		if (role != null && url != null) {
			throw new StrutsException("不正确的标签写法<@auth.authorize/>");
		}

		/* 角色权限判断 */
		if (role != null) {
			if (role.contains(";")) {
				String[] roles = role.split(";");
				if (allAuthorized) {
					return AuthAuthorizeUtil.hasAllRoles(roles);
				} else {
					return AuthAuthorizeUtil.hasAnyRoles(roles);
				}
			} else {
				return AuthAuthorizeUtil.hasRole(role);
			}
		}

		/* URL权限盼断 */
		if (url != null) {
			if (url.contains(";")) {
				String[] urls = url.split(";");
				if (allAuthorized) {
					return AuthAuthorizeUtil.hasAllAuthorize(urls);
				} else {
					return AuthAuthorizeUtil.hasAnyAuthorize(urls);
				}
			} else {
				return AuthAuthorizeUtil.hasAuthorize(url);
			}
		}
		return false;
	}

	@Override
	protected String getDefaultTemplate() {
		return "auth_authorize";
	}

	@Override
	protected boolean evaluateNameValue() {
		return super.evaluateNameValue();
	}

	@Override
	public String getTheme() {
		return "auth";
	}

	@Override
	public boolean start(Writer writer) {
		return authorizeCheck();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public boolean isAllAuthorized() {
		return allAuthorized;
	}

	public void setAllAuthorized(boolean allAuthorized) {
		this.allAuthorized = allAuthorized;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}
}
